package com.gmrz.uap.model;

import com.gmrz.uap.cfg.SystemConst;
import com.gmrz.uap.common.DBCommon;
import com.gmrz.uap.model.base.BaseDevices;
import com.gmrz.uap.util.Identities;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Generated by JFinal.
 */
@SuppressWarnings("serial")
public class Devices extends BaseDevices<Devices> {
    public static final Devices dao = new Devices();

    private static final String NAMESPACE = "devices";
    private static final String SQL_SELECT_COMM = NAMESPACE + SystemConst._DEFAULT_SEPARATOR_DOT + "select_comm";


    /**
     * 根据系统类型获取系统版本
     *
     * @param osType 系统类型
     * @return 系统版本集合 List<String>
     */
    public List<String> getOsVersionByOsType(String osType) {
        String sql = "select os_version from t_devices where os_type = ? group by os_version";
        return Db.query(sql, osType);
    }

    /**
     * 根据系统类型、系统版本、日期获取记录总数
     *
     * @param tenantId  渠道名称
     * @param osType    系统类型
     * @param osVersion 系统版本
     * @param date      查询日期
     * @return 记录总数 Integer
     */
    public Integer getCountByOSTypeOSVersionDate(String tenantId, String osType, String osVersion, String date) {
        String sql = "select count(*) from t_devices where tenant_id = ? and os_type = ? and os_version = ? and createts >= ? and createts < ?";

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = null;
        try {
            d1 = simpleDateFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        return Db.queryInt(sql, tenantId, osType, osVersion,new Date(d1.getTime()),new Date(d1.getTime() + (long)86400000));
    }

    /**
     * 获取设备表中的设备类型集合
     *
     * @return 设备类型集合 List<String>
     */
    public List<String> getDeviceTypeList() {
        String sql = "select device_type from t_devices group by device_type";
        return Db.query(sql);
    }

    public List<String> getDeviceTypeAliasList(){
        String sql = "SELECT device_type_alias from t_device_alias GROUP BY device_type_alias";
        return Db.query(sql);
    }

    public List<String> getDeviceNameAliasList(String deviceNameAlias){
        String sql = "SELECT device_name_alias from t_device_alias WHERE device_type_alias = ? GROUP BY device_name_alias";
        return Db.query(sql,deviceNameAlias);
    }

    public int deleteDeviceAlias() {
        String sql = "delete from t_device_alias";
        return Db.update(sql);
    }

    public void saveDeviceAlias(List<Map<String,String>> list) {
        for(Map<String,String> m : list) {
            String sql = "INSERT INTO t_device_alias(device_alias_id,device_type,device_name,device_type_alias,device_name_alias) VALUES (?,?, ?,?,?)";
            Db.update(sql, Identities.uuid2(), m.get("device_type"),m.get("device_name"),m.get("device_type_alias"),m.get("device_name_alias"));
        }
    }


    /**
     * 根据设备类型获取手机型号集合
     *
     * @return 手机型号集合 List<String>
     */
    public List<String> getDeviceTypeList(String deviceType) {
        String sql = "select device_name from t_devices where device_type = ? group by device_name";
        return Db.query(sql, deviceType);
    }


    /**
     * 根据手机厂商、手机型号、日期获取记录总数
     *
     * @param tenantId   渠道名称
     * @param deviceType 设备类型
     * @param deviceName 手机型号
     * @param date       查询日期
     * @return 记录总数 Integer
     */
    public Integer getCountByDeviceTypeDeviceNameDate(String tenantId, String deviceType, String deviceName, String date) {
        String sql = "select count(*) from t_devices where tenant_id = ? and device_type = ? and device_name = ? and createts >= ? and createts < ?";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = null;
        try {
            d1 = simpleDateFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return Db.queryInt(sql, tenantId, deviceType, deviceName,new Date(d1.getTime()),new Date(d1.getTime() + (long)86400000));
    }


    /**
     * 根据传入的不同参数，拼接成SQL语句进行查询总数
     *
     * @param devices
     * @return Integer
     */
    public Integer getStatisticsCount(Devices devices) {

        StringBuilder sql = new StringBuilder("select count(*) from t_devices where dev_id=dev_id ");

        Iterator<Map.Entry<String, Object>> i = devices._getAttrsEntrySet().iterator();

        //循环遍历传过来的参数，并将参数拼接到SQL
        while (i.hasNext()) {
            Map.Entry<String, Object> obj = i.next();

            if (StrKit.isBlank(obj.getKey()))
                continue;

            //如果数据为空或为NULL的时候，跳过此次循环进入下一次循环
            if (null == obj.getValue() || "" == obj.getValue()) {
                continue;
            }

            if (StringUtils.equalsIgnoreCase(DBCommon.TABLE_DEVICES_COLUMN_DEV_ID, obj.getKey())) {
                sql.append(" and " + obj.getKey() + " = '" + obj.getValue() + "'");
                continue;
            }

            if (StringUtils.equalsIgnoreCase(DBCommon.TABLE_DEVICES_COLUMN_USER_NAME, obj.getKey())) {
                sql.append(" and " + obj.getKey() + " = '" + obj.getValue() + "'");
                continue;
            }

            if (StringUtils.equalsIgnoreCase(DBCommon.TABLE_DEVICES_COLUMN_ALIAS_NAME, obj.getKey())) {
                sql.append(" and " + obj.getKey() + " = '" + obj.getValue() + "'");
                continue;
            }

            if (StringUtils.equalsIgnoreCase(DBCommon.TABLE_DEVICES_COLUMN_TRANS_TYPE, obj.getKey())) {
                sql.append(" and " + obj.getKey() + " = '" + obj.getValue() + "'");
                continue;
            }

            if (StringUtils.equalsIgnoreCase(DBCommon.TABLE_DEVICES_COLUMN_AUTH_TYPE, obj.getKey())) {
                sql.append(" and " + obj.getKey() + " = '" + obj.getValue() + "'");
                continue;
            }

            if (StringUtils.equalsIgnoreCase(DBCommon.TABLE_DEVICES_COLUMN_DEVICE_ID, obj.getKey())) {
                sql.append(" and " + obj.getKey() + " = '" + obj.getValue() + "'");
                continue;
            }

            if (StringUtils.equalsIgnoreCase(DBCommon.TABLE_DEVICES_COLUMN_DEVICE_TYPE, obj.getKey())) {
                sql.append(" and " + obj.getKey() + " = '" + obj.getValue() + "'");
                continue;
            }

            if (StringUtils.equalsIgnoreCase(DBCommon.TABLE_DEVICES_COLUMN_DEVICE_NAME, obj.getKey())) {
                sql.append(" and " + obj.getKey() + " = '" + obj.getValue() + "'");
                continue;
            }

            if (StringUtils.equalsIgnoreCase(DBCommon.TABLE_DEVICES_COLUMN_OS_TYPE, obj.getKey())) {
                sql.append(" and " + obj.getKey() + " = '" + obj.getValue() + "'");
                continue;
            }

            if (StringUtils.equalsIgnoreCase(DBCommon.TABLE_DEVICES_COLUMN_OS_VERSION, obj.getKey())) {
                sql.append(" and " + obj.getKey() + " = '" + obj.getValue() + "'");
                continue;
            }

            if (StringUtils.equalsIgnoreCase(DBCommon.TABLE_DEVICES_COLUMN_STATUS, obj.getKey())) {
                sql.append(" and " + obj.getKey() + " = '" + obj.getValue() + "'");
                continue;
            }

            if (StringUtils.equalsIgnoreCase(DBCommon.TABLE_DEVICES_COLUMN_TENANT_ID, obj.getKey())) {
                sql.append(" and " + obj.getKey() + " = '" + obj.getValue() + "'");
                continue;
            }

            if (StringUtils.equalsIgnoreCase(DBCommon.TABLE_DEVICES_COLUMN_CREATETS, obj.getKey())) {
                sql.append(" and " + obj.getKey() + " like '%" + obj.getValue() + "%'");
                continue;
            }

            if (StringUtils.equalsIgnoreCase(DBCommon.TABLE_DEVICES_COLUMN_UPDATETS, obj.getKey())) {
                sql.append(" and " + obj.getKey() + " like '%" + obj.getValue() + "%'");
                continue;
            }
        }
        return Db.queryInt(sql.toString());
    }


    /**
     * 获取表中最小的时间
     *
     * @return
     */
    public DateTime getEarliestDate() {
        DateTime dateTime;
        String minDate = Db.queryStr(this.getSql(NAMESPACE + SystemConst._DEFAULT_SEPARATOR_DOT + "getEarliestDate"));

        if (StrKit.isBlank(minDate)) {//如果返回为空代表数据库中还没有数据，则返回当前时间
            dateTime = new DateTime();
        } else {
            dateTime = new DateTime(minDate);
        }
        return dateTime;
    }

}
